<!-- 考试题库 -->
<template>
  <div class="exam-container flex-center">
    <div v-loading="treeLoading" class="left-content">
      <div class="tree-title">
        <span>题目分类</span>
      </div>
      <div class="tree-search">
        <px-input v-model="treeSearchVal" placeholder="请输入" :prefix-icon="Search" clearable @change="getTreeData" />
      </div>
      <div class="tree-bar">
        <px-scrollbar>
          <px-tree
            ref="treeRef"
            :data="treeData"
            node-key="id"
            default-expand-all
            highlight-current
            :current-node-key="currentNode"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          />
        </px-scrollbar>
      </div>
    </div>
    <div class="right-content">
      <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
        <px-form-item label="题目类型" prop="questionType">
          <px-select v-model="queryParams.questionType" style="width: 260px" placeholder="请选择题目类型" clearable>
            <px-option v-for="item in questionTypeList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="题目名称" prop="questionName">
          <px-input v-model="queryParams.questionName" style="width: 260px" placeholder="请输入题目名称" clearable />
        </px-form-item>
        <div class="search-form-btn">
          <px-button type="primary" @click="handleQuery">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
        </div>
      </px-form>
      <div class="flex-center mg-b-8">
        <px-button v-has="'ALL_EXAMMANAGE_EXAMQUESTIONBANK_CLASS_MANAGE'" type="primary" @click="handleClassify">分类管理</px-button>
        <px-button v-has="'ALL_EXAMMANAGE_EXAMQUESTIONBANK_ADD'" type="primary" @click="handleAdd">新增</px-button>
        <px-button v-has="'ALL_EXAMMANAGE_EXAMQUESTIONBANK_DOWNLOAD_TEMPLATE'" type="primary" plain @click="handleDownloadTemplate"
          >下载模板</px-button
        >
        <px-upload action="#" :http-request="handleImport" :show-file-list="false" accept=".xlsx, xls" style="margin: 0 16px">
          <px-button v-has="'ALL_EXAMMANAGE_EXAMQUESTIONBANK_IMPORT'" type="primary" plain>批量导入</px-button>
        </px-upload>
        <px-button v-has="'ALL_EXAMMANAGE_EXAMQUESTIONBANK_DOWNLOAD'" type="primary" plain @click="handleExport">导出</px-button>
      </div>
      <div v-loading="loading" class="table-content">
        <px-table height="calc(100vh - 340px)" :data="tableData" size="small" border class="common-table">
          <px-table-column type="index" label="序号" fixed width="55" align="center" />
          <px-table-column prop="name" label="题目名称" min-width="120" show-overflow-tooltip>
            <template #default="scope">
              <span v-html="scope.row.name" />
            </template>
          </px-table-column>
          <px-table-column prop="typeName" label="题目类型" min-width="120" show-overflow-tooltip />
          <px-table-column prop="score" label="分值" min-width="120" show-overflow-tooltip />
          <px-table-column prop="updateTime" label="更新时间" min-width="120" show-overflow-tooltip />
          <px-table-column prop="updateByName" label="更新人" min-width="120" show-overflow-tooltip />
          <px-table-column label="操作" width="120" fixed="right" align="center">
            <template #default="scope">
              <px-tooltip content="编辑" placement="top">
                <px-button v-has="'ALL_EXAMMANAGE_EXAMQUESTIONBANK_EDIT'" link icon="EditPen" type="primary" @click="handleEdit(scope.row)" />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button v-has="'ALL_EXAMMANAGE_EXAMQUESTIONBANK_DELETE'" link icon="Delete" type="danger" @click="handleDelete(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="pageNum"
          v-model:limit="pageSize"
          class="table-pagination"
          :total="total"
          @pagination="handleQuery"
        />
      </div>
    </div>
    <div v-if="classifyVisible">
      <Classification v-model:visible="classifyVisible" @refresh="getTreeData" />
    </div>

    <div v-if="addSubjectVisible">
      <AddSubject
        v-model:visible="addSubjectVisible"
        :title="addSubjectTitle"
        :categoryId="currentNode"
        :questionId="rowData?.questionId"
        @save="saveQuestion"
      />
    </div>

    <!-- 导入失败提示弹窗 -->
    <px-dialog v-model="uploadErrorVisible" title="导入失败" width="800">
      <ul class="error-list">
        <li v-for="item in uploadErrorList" :key="item">
          {{ item }}
        </li>
      </ul>
    </px-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, nextTick, watch, getCurrentInstance } from "vue";
import { Search } from "@px-ui/icons-vue";
import Classification from "./component/classification.vue";
import AddSubject from "../component/addSubject.vue";
import { getQuestionCategoryListAPI, getQuestionListAPI, saveQuestionAPI, deleteQuestionAPI, uploadAPI } from "@/api/knowledge/examManage";
import { PxMessage, PxMessageBox } from "px-ui";

defineOptions({
  name: "ALL_EXAMMANAGE_EXAMQUESTIONBANK"
});

const treeRef = ref(null);
const formRef = ref(null);

const state = reactive({
  treeLoading: false,
  treeData: [],
  treeSearchVal: "",
  currentNode: "0",
  queryParams: {
    questionType: "",
    questionName: ""
  },
  questionTypeList: [
    {
      name: "单选",
      value: "S"
    },
    {
      name: "多选",
      value: "M"
    },
    {
      name: "判断",
      value: "T"
    }
  ],
  loading: false,
  tableData: [],
  total: 1,
  pageNum: 1,
  pageSize: 20,
  classifyVisible: false,
  addSubjectVisible: false,
  addSubjectTitle: "",
  rowData: {},
  uploadErrorVisible: false,
  uploadErrorList: []
});
const {
  treeLoading,
  treeData,
  treeSearchVal,
  currentNode,
  queryParams,
  questionTypeList,
  loading,
  tableData,
  total,
  pageNum,
  pageSize,
  classifyVisible,
  addSubjectVisible,
  addSubjectTitle,
  rowData,
  uploadErrorVisible,
  uploadErrorList
} = toRefs(state);

onMounted(() => {
  getTreeData();
});

watch(treeSearchVal, val => {
  treeRef.value.filter(val);
});

const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.includes(value);
};

const getTreeData = async () => {
  try {
    state.treeLoading = true;
    const params = {
      size: 9999,
      current: 1,
      name: state.treeSearchVal
    };
    const res = await getQuestionCategoryListAPI(params);
    state.treeData = res.records.map(item => {
      return {
        id: item.categoryId,
        label: item.category,
        children: []
      };
    });
    nextTick(() => {
      state.currentNode = res.records[0].id;
      treeRef.value.setCurrentKey(res.records[0].id);
      handleQuery();
    });
  } catch (err) {
    console.log(err);
  } finally {
    state.treeLoading = false;
  }
};

// 点击树节点
const handleNodeClick = (data, node, obj) => {
  state.currentNode = data.id;
  handleQuery();
};

// 查询
const handleQuery = async () => {
  try {
    state.loading = true;
    const params = {
      categoryId: state.currentNode,
      questionType: state.queryParams.questionType,
      questionName: state.queryParams.questionName,
      size: state.pageSize,
      current: state.pageNum
    };
    const res = await getQuestionListAPI(params);
    state.tableData = res.records;
    state.total = res.total;
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  handleQuery();
};

// 分类管理
const handleClassify = () => {
  state.classifyVisible = true;
};

// 新增
const handleAdd = () => {
  state.rowData = {};
  state.addSubjectTitle = "新增题目";
  state.addSubjectVisible = true;
};

// 编辑
const handleEdit = row => {
  state.rowData = row;
  state.addSubjectTitle = "编辑题目";
  state.addSubjectVisible = true;
};

// 下载模板
const handleDownloadTemplate = () => {
  const fileUrl = "/models/题库导入模板.xlsx";

  // 创建一个隐藏的a标签
  const link = document.createElement("a");
  link.href = fileUrl;

  // 将a标签添加到DOM并触发点击事件
  document.body.appendChild(link);
  link.click();

  // 移除a标签
  document.body.removeChild(link);
};

// 批量导入
const handleImport = async options => {
  try {
    state.loading = true;
    const { file } = options;
    const formData = new FormData();
    formData.append("file", file);
    const res = await uploadAPI(formData);
    // if (res.length > 0) {
    //   state.uploadErrorList = res.split("#");
    //   state.uploadErrorVisible = true;
    // } else {
    PxMessage.success("批量导入成功");
    // }
    console.log(res);
    handleQuery();
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};
const { proxy } = getCurrentInstance();
// 导出
const handleExport = () => {
  let params = {
    categoryId: "", // 题目分类ID
    questionType: "" // 	题目类型
  };
  proxy.download("post", "/dms/api/v1/exam/exportQuestion", params);
};

// 删除
const handleDelete = row => {
  PxMessageBox.confirm("确定删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      await deleteQuestionAPI({ questionId: row.questionId });
      PxMessage.success("删除成功");
      handleQuery();
    })
    .catch(() => {});
};

const saveQuestion = async params => {
  await saveQuestionAPI(params);
  state.addSubjectVisible = false;
  PxMessage.success(state.addSubjectTitle === "新增题目" ? "新增成功" : "编辑成功");
  handleQuery();
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/knowledge/examManage/scss/common.scss");

.left-content {
  width: 316px;
  height: 100%;
  border: 1px solid #dfdfdf;
  border-radius: 4px;

  .tree-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 8px 0;
    font-size: 14px;
    font-weight: bold;
  }

  .tree-search {
    padding: 8px;
  }

  .tree-bar {
    width: 100%;
    height: calc(100vh - 340px);
    overflow-y: auto;
  }
}

.right-content {
  width: calc(100% - 316px);
  height: 100%;
  padding-left: 18px;
}
</style>
